package edi.android.tmdbBrowser;

import java.util.List;
import java.util.Set;

import net.sf.jtmdb.Movie;
import net.sf.jtmdb.MoviePoster;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

// Adapter class for the top 10 gallery
/**
 * @author edi
 * 
 */
public class MovieGalleryAdapter extends BaseAdapter {
	private Context context;
	private List<Movie> movies;

	/**
	 * @param c
	 *            Context
	 * @param m
	 *            List of movies
	 */
	public MovieGalleryAdapter(Context c, List<Movie> m) {
		context = c;
		movies = m;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		if (movies != null) {
			return movies.size();
		}
		return 0;
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		if (movies != null) {
			return movies.get(arg0);
		}
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		if (movies != null) {
			return movies.get(position).getID();
		}
		return -1;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.widget.Adapter#getView(int, android.view.View,
	 * android.view.ViewGroup)
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final Set<MoviePoster> posters;
		ImageView imageView = (ImageView) convertView;

		if (imageView == null) {
			imageView = new ImageView(context);
			imageView.setPadding(6, 6, 6, 6);
			imageView.setAdjustViewBounds(true);
			imageView.setImageDrawable(context.getResources().getDrawable(
					R.drawable.nocover));
		}

		// check if the movie got an usable poster
		posters = movies.get(position).getImages().posters;
		if (posters != null && !posters.isEmpty()) {
			TMDbApp.imageDownloader.download(posters.iterator().next()
					.getSmallestImage().toString(), imageView);
		} else {
			TMDbApp.imageDownloader.download(
					"http://hwcdn.themoviedb.org/images/no-poster-small.png",
					imageView);
		}

		return imageView;
	}

}